import { Header } from "./styled"
import { useModel, history } from '@umijs/max'
import { DownOutlined, UserOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Dropdown, Form, Input, Modal, Space } from 'antd';
import { useState } from "react";
import request from "@/utils/request"
import { useRequest } from "ahooks";
import { LoginType } from "@/pages/Login/services";

async function editPsd(params: {old: string, password: string}) {
  return request('/app/manager/user/changePass', {
    data: params,
  })
}

const items: MenuProps['items'] = [
  {
    label: '修改密码',
    key: 'editPassword',
  },
  {
    label: '退出登录',
    key: 'logout',
  },
];

const useHeader: React.FC = () => {
  const { setInitialState } = useModel('@@initialState')
  const { removeAll } = useModel('global')
  const [open, setOpen] = useState(false);
  const [updatePsdForm] = Form.useForm()
  const { runAsync, loading } = useRequest(editPsd, {manual: true})

  const logout = () => {
    const userType = sessionStorage.userType
    if (userType === String(LoginType.大客户登录)) {
      localStorage.removeItem('Authorization2')
    } else {
      localStorage.removeItem('Authorization')
    }
    setInitialState({menuList: []}).then(() => {
      removeAll()
      let originHref: string
      if (window.location.href.includes('redirect=')) {
        originHref = window.location.href.split('redirect=').at(-1) || '/'
      } else {
        originHref = encodeURIComponent(window.location.href)
      }
      if (userType === String(LoginType.大客户登录)) {
        history.replace(`/vipLogin?redirect=${originHref}`)
      } else {
        history.replace(`/login?redirect=${originHref}`)
      }
    })
  }

  const onClick = ({key}: {key: string}) => {
    switch (key) {
      case 'editPassword': setOpen(true); break
      case 'logout': logout(); break
    }
  }

  const onCancel = () => {
    setOpen(false)
  }

  const onOk = () => {
    updatePsdForm.validateFields().then(values => {
      runAsync(values).then(() => {
        onCancel()
        logout()
      })
    })
  }

  return (
    <Header>
      <Dropdown menu={{ items, onClick }} trigger={['click']}>
        <Space style={{cursor: 'pointer'}}>
          <Space>
            <UserOutlined />
            <span>{sessionStorage.username || ''}</span>
          </Space>
          <DownOutlined />
        </Space>
      </Dropdown>
      <Modal
        open={open}
        title='修改密码'
        width={520}
        onCancel={onCancel}
        onOk={onOk}
        confirmLoading={loading}
      >
        <Form form={updatePsdForm} labelCol={{span: 6}}>
          <Form.Item name='old' label='旧密码' rules={[{required: true, message: '请输入旧密码'}]}>
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item name='password' label='新密码' rules={[{required: true, message: '请输入旧密码'}]}>
            <Input.Password />
          </Form.Item>
          <Form.Item
            name="confirm"
            label="确认新密码"
            dependencies={['password']}
            hasFeedback
            rules={[
              {
                required: true,
                message: '请输入新密码',
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('密码不一致!'));
                },
              }),
            ]}
          >
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>
    </Header>
  )
}

export default useHeader